<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>支付详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              v-if="paymentData.status === '待支付'"
              @click="handleProcess"
              v-permission="'payment:update'"
            >
              处理支付
            </el-button>
            <el-button 
              type="danger" 
              v-if="paymentData.status === '待支付'"
              @click="handleCancel"
              v-permission="'payment:delete'"
            >
              取消支付
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div class="detail-content" v-if="!loading && paymentData.id">
        <!-- 支付基本信息 -->
        <el-descriptions title="支付基本信息" :column="3" border>
          <el-descriptions-item label="支付编号">{{ paymentData.paymentId }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getStatusType(paymentData.status)">{{ paymentData.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ paymentData.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="支付金额">{{ paymentData.amount?.toFixed(2) }} 元</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ paymentData.totalAmount?.toFixed(2) }} 元</el-descriptions-item>
          <el-descriptions-item label="交易流水号">{{ paymentData.transactionId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(paymentData.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ paymentData.paidAt ? formatDateTime(paymentData.paidAt) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(paymentData.updatedAt) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 患者信息 -->
        <el-descriptions title="患者信息" :column="3" border class="mt-20">
          <el-descriptions-item label="患者ID">{{ patientInfo.patientId }}</el-descriptions-item>
          <el-descriptions-item label="患者姓名">{{ patientInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ patientInfo.gender }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ patientInfo.age }}</el-descriptions-item>
        </el-descriptions>

        <!-- 支付项目列表 -->
        <div class="mt-20">
          <h4>支付项目</h4>
          <el-table :data="paymentData.items || []" border style="width: 100%">
            <el-table-column label="项目类型" prop="type" min-width="150">
              <template #default="scope">
                {{ getItemTypeName(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column label="项目ID" prop="itemId" min-width="200" />
            <el-table-column label="金额" prop="amount" min-width="120">
              <template #default="scope">
                {{ scope.row.amount?.toFixed(2) }} 元
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <el-empty v-else-if="!loading && !paymentData.id" description="未找到支付记录" />
    </el-card>

    <!-- 处理支付弹窗 -->
    <el-dialog
      title="处理支付"
      v-model="processDialog.visible"
      width="500px"
    >
      <el-form :model="processDialog.form" label-width="120px" ref="processFormRef">
        <el-form-item label="支付状态" prop="status">
          <el-select v-model="processDialog.form.status" placeholder="请选择支付状态" style="width: 100%">
            <el-option label="成功" value="成功" />
            <el-option label="失败" value="失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号" prop="transactionId">
          <el-input v-model="processDialog.form.transactionId" placeholder="请输入交易流水号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmProcess" :loading="processDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { paymentAPI } from '@/utils/api'
import { formatDateTime } from '@/utils/format'

const router = useRouter()
const route = useRoute()
const paymentId = ref(route.params.id)

// 支付数据
const loading = ref(false)
const paymentData = ref({})
const patientInfo = ref({})

// 处理支付对话框
const processDialog = reactive({
  visible: false,
  loading: false,
  form: {
    status: '成功',
    transactionId: ''
  }
})

// 获取支付详情
const fetchPaymentDetail = async () => {
  if (!paymentId.value) return
  
  loading.value = true
  try {
    const res = await paymentAPI.getPaymentDetail(paymentId.value)
    console.log('支付详情响应:', res) // 添加日志查看实际响应结构
    
    // 根据返回格式获取数据
    const { payment, patientInfo: patient } = res.data
    paymentData.value = payment || {}
    patientInfo.value = patient || {}
    
  } catch (error) {
    console.error('获取支付详情失败', error)
    console.log('错误详情:', error.message, error.response || error)
    // 拦截器已经显示错误消息，这里不需要重复显示
  } finally {
    loading.value = false
  }
}

// 获取项目类型名称
const getItemTypeName = (type) => {
  const map = {
    'registration': '挂号费',
    'prescription': '处方费',
    'medical_record': '病历费',
    'service': '服务费',
    'other': '其他费用'
  }
  return map[type] || type
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    paymentId.value = newId
    // 清空之前的数据
    paymentData.value = {}
    patientInfo.value = {}
    // 重新获取数据
    fetchPaymentDetail()
  }
}, { immediate: true })

// 处理支付
const handleProcess = () => {
  processDialog.form.status = '成功'
  processDialog.form.transactionId = ''
  processDialog.visible = true
}

// 确认处理支付
const confirmProcess = async () => {
  processDialog.loading = true
  try {
    const res = await paymentAPI.processPayment(
      paymentId.value,
      {
        status: processDialog.form.status,
        transactionId: processDialog.form.transactionId
      }
    )
    
    ElMessage.success('支付处理成功')
    processDialog.visible = false
    fetchPaymentDetail()
    
  } catch (error) {
    console.error('支付处理失败', error)
    console.log('错误详情:', error.message, error.response || error)
    // 拦截器已经显示错误消息，这里不需要重复显示
  } finally {
    processDialog.loading = false
  }
}

// 取消支付
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消此支付记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await paymentAPI.cancelPayment(paymentId.value)
      
      ElMessage.success('支付已取消')
      fetchPaymentDetail()
      
    } catch (error) {
      console.error('取消支付失败', error)
      console.log('错误详情:', error.message, error.response || error)
      // 拦截器已经显示错误消息，这里不需要重复显示
    }
  }).catch(() => {})
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    '待支付': 'warning',
    '已支付': 'success',
    '成功': 'success',
    '已取消': 'info',
    '已退款': 'danger'
  }
  return map[status] || 'info'
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-actions {
  display: flex;
  gap: 10px;
}
.mt-20 {
  margin-top: 20px;
}
</style> 